public class Code_24 {
    public ListNode swapPairs(ListNode head) {
        // 1 2 3 4
        if (head==null){ //链表为空
            return null;
        } else if (head.next ==null) { //链表只有一个元素
            return head;
        }
        ListNode left = head;
        ListNode right= left.next;
        head = head.next;  //先确定头结点
        swap(left,right); // 交换相邻节点
        while (left.next!=null){
            ListNode pre =new ListNode();
            pre =left;
            left = left.next;
            right = left.next;
            if (right==null){
                break;
            }
            swap(left,right); //交换相邻节点
            pre.next=right;
        }
        return head;
    }

    public void swap(ListNode left,ListNode right){
        ListNode tmp = right.next;
        left.next = tmp;
        right.next = left;
    }
}
